<template>
  <div class="interview-container">
    <!-- 使用Element Plus日历组件 -->
    <div class="calendar-section">
      <el-calendar v-model="selectedDate" @change="handleDateSelect">
        <!-- 自定义日历单元格 -->
        <template #date-cell="{ data }">
          <div class="calendar-cell" :class="{'has-interviews': hasInterviewsOnDate(data.day)}">
            <p>{{ data.day.split('-')[2] }}</p>
            <div v-if="hasInterviewsOnDate(data.day)" class="interview-dot"></div>
          </div>
        </template>
      </el-calendar>
    </div>

    <!-- 面试列表部分 -->
    <div class="interviews-section" v-loading="loading">
      <div class="selected-date">
        <span>{{ formatSelectedDate(selectedDate) }}的面试安排</span>
      </div>
      <div v-if="interviewList.length > 0">
        <div 
          class="interview-card" 
          v-for="item in interviewList" 
          :key="item.id"
          :class="{
            'status-upcoming': item.status === '即将面试',
            'status-waiting': item.status === '待面试',
            'status-feedback': item.status === '待反馈'
          }"
        >
          <div class="interview-header">
            <span class="interviewee-name">{{ item.name }}</span>
            <span class="position">{{ item.jobName }}</span>
            <span class="phone">{{ item.phone }}</span>
            <span class="interview-time">面试时间: {{ formatDateTime(item.interviewTime) }} {{ item.interviewTimeOfDay }}</span>
            <span v-if="item.status" class="interview-status" 
                  :class="{
                    'status-upcoming': item.status === '即将面试',
                    'status-waiting': item.status === '待面试',
                    'status-feedback': item.status === '待反馈'
                  }">{{ item.status }}</span>
          </div>
          
          <div class="interview-info">
            <div class="score-info">
              <span>匹配分数: {{ item.matchScore || 98 }} 分</span>
              <span class="interview-type">{{ item.interviewType || '初面' }}</span>
            </div>
            
            <!-- 显示状态对应的操作按钮 -->
            <div class="interview-actions">
              <!-- 即将面试的状态 -->
              <template v-if="item.status === '即将面试'">
                <el-button size="small" @click="uploadReport(item.id)">上传测评报告</el-button>
                <el-button size="small" @click="addInterviewFeedback(item.id)">填写面评</el-button>
                <el-button size="small" @click="markUnsuitable(item.id)">不合适</el-button>
                <el-button size="small" @click="addToReserve(item.id)">储备</el-button>
                <el-button size="small" @click="sendOffice(item.id)" type="primary">发送office</el-button>
              </template>
              
              <!-- 待面试的状态 -->
              <template v-else-if="item.status === '待面试'">
                <el-button size="small" @click="checkIn(item.id)">牛人未到</el-button>
                <el-button size="small" @click="uploadReport(item.id)">上传测评报告</el-button>
                <el-button size="small" @click="addInterviewFeedback(item.id)">填写面评</el-button>
                <el-button size="small" @click="markUnsuitable(item.id)">不合适</el-button>
                <el-button size="small" @click="addToReserve(item.id)">储备</el-button>
                <el-button size="small" @click="sendOffice(item.id)" type="primary">发送office</el-button>
              </template>
              
              <!-- 待反馈的状态 -->
              <template v-else-if="item.status === '待反馈'">
                <el-button size="small" @click="uploadReport(item.id)">上传测评报告</el-button>
                <el-button size="small" @click="addInterviewFeedback(item.id)">填写面评</el-button>
                <el-button size="small" @click="markUnsuitable(item.id)">不合适</el-button>
                <el-button size="small" @click="addToReserve(item.id)">储备</el-button>
                <el-button size="small" @click="sendOffice(item.id)" type="primary">发送office</el-button>
              </template>
              
              <!-- 默认按钮 -->
              <template v-else>
                <el-button size="small" @click="uploadReport(item.id)">上传测评报告</el-button>
                <el-button size="small" @click="addInterviewFeedback(item.id)">填写面评</el-button>
                <el-button size="small" @click="markUnsuitable(item.id)">不合适</el-button>
                <el-button size="small" @click="addToReserve(item.id)">储备</el-button>
                <el-button size="small" @click="sendOffice(item.id)" type="primary">发送office</el-button>
              </template>
            </div>
          </div>
          
          <!-- 测评报告部分 (如果有) -->
          <div class="evaluation-report" v-if="item.report">
            <h4>16pf报告:</h4>
            <p>{{ item.report }}</p>
          </div>
          
          <!-- 面试官评语 (如果有) -->
          <div class="interview-feedback" v-if="item.feedback">
            <h4>面试官评语:</h4>
            <p>{{ item.feedback }}</p>
          </div>
          
          <!-- HR评语 (如果有) -->
          <div class="hr-feedback" v-if="item.hrFeedback">
            <h4>HR评语:</h4>
            <p>{{ item.hrFeedback }}</p>
          </div>
        </div>
      </div>
      <el-empty v-else description="暂无面试数据" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { PersonnelResumeApi } from '@/api/hrm/personnelresume'

// 定义props
const props = defineProps<{
  // 可添加需要的props
}>()

// 面试数据
const loading = ref(false)
const interviewList = ref<any[]>([])
const interviewsMap = ref<Record<string, any[]>>({})
const selectedDate = ref(new Date())

// 模拟数据
const mockInterviews = [
  {
    id: '1',
    name: '何升业',
    jobName: '前端开发工程师',
    phone: '15234336917',
    interviewTime: new Date('2025-05-01 15:30').getTime(),
    interviewTimeOfDay: '',
    matchScore: 98,
    interviewType: '初面',
    status: '即将面试'
  },
  {
    id: '2',
    name: '何升业',
    jobName: '前端开发工程师',
    phone: '15234336917',
    interviewTime: new Date('2025-05-01 15:30').getTime(),
    interviewTimeOfDay: '',
    matchScore: 98,
    interviewType: '初面',
    status: '即将面试'
  },
  {
    id: '3',
    name: '何升业',
    jobName: '前端开发工程师',
    phone: '15234336917',
    interviewTime: new Date('2025-05-01 15:30').getTime(),
    interviewTimeOfDay: '',
    matchScore: 98,
    interviewType: '初面',
    status: '待面试'
  },
  {
    id: '4',
    name: '何升业',
    jobName: '前端开发工程师',
    phone: '15234336917',
    interviewTime: new Date('2025-05-01 15:30').getTime(),
    interviewTimeOfDay: '',
    matchScore: 98,
    interviewType: '初面',
    status: '待反馈',
    report: '性格特点：乐观、外向、喜欢与人交流，具有良好的沟通能力和团队协作精神。\n技能评估：JavaScript基础扎实，React熟练，有3年前端开发经验。',
    feedback: '技术能力：React基础扎实，对组件设计有自己的见解，能够解决常见的性能问题。\n沟通能力：表达清晰，能够理解业务需求并转化为技术实现。\n团队协作：之前项目经验丰富，善于与后端开发协作。',
    hrFeedback: '面试表现良好，符合团队文化，建议进入下一轮技术面试。薪资期望在25K-30K之间，可接受夜班和加班。'
  }
]

// 创建模拟的日历数据
const createMockCalendarData = () => {
  const now = new Date()
  const currentMonth = now.getMonth()
  const currentYear = now.getFullYear()
  
  // 为当前月的几天添加面试数据
  const dates = [1, 5, 10, 15, 20, 25]
  const mockMap: Record<string, any[]> = {}
  
  dates.forEach(day => {
    const date = new Date(currentYear, currentMonth, day)
    const dateStr = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    
    mockMap[dateStr] = mockInterviews.map(interview => ({
      ...interview,
      interviewTime: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 10, 30).getTime()
    }))
  })
  
  // 当天也添加面试数据
  const today = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`
  mockMap[today] = mockInterviews
  
  return mockMap
}

// 格式化日期时间
const formatDateTime = (timestamp: number) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 格式化选中日期显示
const formatSelectedDate = (date: Date) => {
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}

// 检查某日期是否有面试
const hasInterviewsOnDate = (dateStr: string) => {
  const formattedDate = dateStr.split('T')[0] // 处理ISO日期格式
  return !!interviewsMap.value[formattedDate] && interviewsMap.value[formattedDate].length > 0
}

// 日期选择处理
const handleDateSelect = (date: Date) => {
  selectedDate.value = date
  fetchInterviewsForDate(date)
}

// 获取指定日期的面试列表
const fetchInterviewsForDate = async (date: Date) => {
  loading.value = true
  try {
    const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    
    // 使用新的面试分页API，暂时不传递viewTime参数
    const response = await PersonnelResumeApi.getPersonnelInterviewPage({
      pageNo: 1,
      pageSize: 10
    })
    
    // 如果API返回数据为空，使用模拟数据
    if (!response.list || response.list.length === 0) {
      interviewList.value = interviewsMap.value[formattedDate] || mockInterviews
    } else {
      // 处理API返回的数据，将其转换为组件需要的格式
      interviewList.value = response.list.map(item => {
        return {
          id: item.id,
          name: item.name || '',
          jobName: item.jsonName || '',
          phone: item.phone || '',
          interviewTime: item.viewTime ? new Date(item.viewTime).getTime() : 0,
          interviewTimeOfDay: '',
          matchScore: item.resumeSource || 98,
          interviewType: item.viewName || '初面',
          status: mapViewStateToStatus(item.viewState),
          report: item.assessUrl ? '查看测评报告' : '',
          feedback: item.evaluate || '',
          hrFeedback: item.hrEvaluate || '',
          resumeComment: item.resumeComment || ''
        }
      })
    }
  } catch (error) {
    console.error('Failed to fetch interviews:', error)
    ElMessage.warning('使用模拟数据显示面试列表')
    
    // 发生错误时使用模拟数据
    const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    interviewList.value = interviewsMap.value[formattedDate] || mockInterviews
  } finally {
    loading.value = false
  }
}

// 获取所有面试数据，用于日历标记
const fetchAllInterviews = async () => {
  try {
    // 使用新的面试分页API获取面试数据，暂时不传递viewTime参数
    const response = await PersonnelResumeApi.getPersonnelInterviewPage({
      pageNo: 1,
      pageSize: 100  // 修改为100，符合API最大限制
    })
    
    // 将面试数据按日期分组
    if (response.list && response.list.length > 0) {
      interviewsMap.value = {}
      response.list.forEach(interview => {
        if (interview.viewTime) {
          const date = new Date(interview.viewTime)
          const dateStr = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
          
          if (!interviewsMap.value[dateStr]) {
            interviewsMap.value[dateStr] = []
          }
          
          // 转换数据格式
          interviewsMap.value[dateStr].push({
            id: interview.id,
            name: interview.name || '',
            jobName: interview.jsonName || '',
            phone: interview.phone || '',
            interviewTime: date.getTime(),
            interviewTimeOfDay: '',
            matchScore: interview.resumeSource || 98,
            interviewType: interview.viewName || '初面',
            status: mapViewStateToStatus(interview.viewState),
            report: interview.assessUrl ? '查看测评报告' : '',
            feedback: interview.evaluate || '',
            hrFeedback: interview.hrEvaluate || '',
            resumeComment: interview.resumeComment || ''
          })
        }
      })
    } else {
      // 如果API没有返回数据，使用模拟数据
      interviewsMap.value = createMockCalendarData()
    }
  } catch (error) {
    console.error('Failed to fetch all interviews:', error)
    ElMessage.warning('使用模拟数据显示日历')
    
    // 发生错误时使用模拟数据
    interviewsMap.value = createMockCalendarData()
  }
}

// 映射API返回的viewState到组件中使用的status
const mapViewStateToStatus = (viewState?: string) => {
  if (!viewState) return '待面试'
  
  // 根据实际情况定义映射关系
  const stateMap: Record<string, string> = {
    '0': '待面试',
    '1': '即将面试',
    '2': '待反馈',
    '3': '已完成'
  }
  
  return stateMap[viewState] || '待面试'
}

// 操作按钮的处理函数
const uploadReport = (id: string) => {
  ElMessage.info(`上传测评报告 ID: ${id}`)
  // 实际实现
}

const addInterviewFeedback = (id: string) => {
  ElMessage.info(`填写面评 ID: ${id}`)
  // 实际实现
}

const markUnsuitable = (id: string) => {
  ElMessage.info(`标记不合适 ID: ${id}`)
  // 实际实现
}

const addToReserve = (id: string) => {
  ElMessage.info(`添加到储备 ID: ${id}`)
  // 实际实现
}

const sendOffice = (id: string) => {
  ElMessage.info(`发送office ID: ${id}`)
  // 实际实现
}

// 牛人未到处理函数
const checkIn = (id: string) => {
  ElMessage.info(`牛人未到 ID: ${id}`)
  // 实际实现
}

// 组件挂载时加载数据
onMounted(() => {
  // 先使用模拟数据
  interviewList.value = mockInterviews
  interviewsMap.value = createMockCalendarData()
  
  // 然后尝试从API获取数据
  fetchInterviewsForDate(selectedDate.value)
  fetchAllInterviews()
})
</script>

<style lang="scss" scoped>
.interview-container {
  display: flex;
  gap: 20px;
  
  .calendar-section {
    flex: 0 0 340px;
    background-color: #f5f7fa;
    border-radius: 4px;
    padding: 15px;
    
    :deep(.el-calendar) {
      background: transparent;
      border: none;
      
      .el-calendar__header {
        border-bottom: 1px solid #e4e7ed;
        padding: 0 0 10px 0;
      }
      
      .el-calendar__body {
        padding: 0;
      }
      
      .calendar-cell {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        position: relative;
        
        .interview-dot {
          position: absolute;
          bottom: 5px;
          width: 6px;
          height: 6px;
          background-color: #f56c6c;
          border-radius: 50%;
        }
      }
    }
  }
  
  .interviews-section {
    flex: 1;
    
    .selected-date {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #e4e7ed;
    }
    
    .interview-card {
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      padding: 15px;
      margin-bottom: 15px;
      border-left: 4px solid transparent;
      
      &.status-upcoming {
        border-left-color: #409eff;
      }
      
      &.status-waiting {
        border-left-color: #e6a23c;
      }
      
      &.status-feedback {
        border-left-color: #67c23a;
      }
      
      .interview-header {
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        
        .interviewee-name {
          font-size: 16px;
          font-weight: bold;
          margin-right: 10px;
        }
        
        .position {
          margin-right: 10px;
          color: #333;
        }
        
       .phone {
          color: #666;
          margin-right: 15px;
        }
        
        .interview-time {
          color: #409eff;
          font-weight: bold;
          margin-right: 15px;
        }
        
        .interview-status {
          padding: 2px 8px;
          border-radius: 10px;
          font-size: 12px;
          font-weight: bold;
          
          &.status-upcoming {
            background-color: #ecf5ff;
            color: #409eff;
          }
          
          &.status-waiting {
            background-color: #fdf6ec;
            color: #e6a23c;
          }
          
          &.status-feedback {
            background-color: #f0f9eb;
            color: #67c23a;
          }
          
          &:not(:empty):not(.status-upcoming):not(.status-waiting):not(.status-feedback) {
            background-color: #f4f4f5;
            color: #909399;
          }
        }
      }
      
      .interview-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        
        .score-info {
          color: #666;
          
          .interview-type {
            margin-left: 15px;
            color: #409eff;
          }
        }
        
        .interview-actions {
          display: flex;
          gap: 5px;
          flex-wrap: wrap;
        }
      }
      
      .evaluation-report,
      .interview-feedback,
      .hr-feedback {
        background-color: #f5f7fa;
        padding: 10px;
        margin-top: 10px;
        border-radius: 4px;
        
        h4 {
          margin: 0 0 5px 0;
          color: #333;
        }
        
        p {
          margin: 0;
          color: #666;
          line-height: 1.5;
        }
      }
    }
  }
}
</style>
